<template>
  <!-- 操作按钮区 -->
  <div class="action-buttons">

    <el-button type="success" @click="batchSaveDetails" class="add-button">添加</el-button>
  </div>

  <div>
    <!-- 查询条件部分 -->
    <div class="search-section">
      <el-form :inline="true" :model="prolist">
        <el-form-item label="工厂">
          <el-input v-model="prolist.factory" placeholder="输入关联项目"></el-input>
        </el-form-item>
        <el-form-item label="事务时间">
          <el-date-picker v-model="prolist.transactionTime" type="date" placeholder="选择日期"></el-date-picker>-
          <el-date-picker v-model="prolist.transactionEndTime" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="工单号">
          <el-input v-model="prolist.workOrderNo" placeholder="输入领料编号"></el-input>
        </el-form-item>
        <el-form-item label="成品产品批次号">
          <el-input v-model="prolist.finishedProductBatch" placeholder="输入领料主题"></el-input>
        </el-form-item>
        <el-form-item label="产线">
          <el-input v-model="prolist.productionLine" placeholder="输入添加人员"></el-input>
        </el-form-item>
        <el-form-item label="班组">
          <el-input v-model="prolist.team" placeholder="输入添加人员"></el-input>
        </el-form-item>
        <el-form-item label="班次">
          <el-input v-model="prolist.shift" placeholder="输入添加人员"></el-input>
        </el-form-item>
        <el-form-item label="物料编码">
          <el-input v-model="prolist.materialCode" placeholder="输入添加人员"></el-input>
        </el-form-item>
        <el-form-item label="入出类型">
          <el-input v-model="prolist.accessType" placeholder="输入添加人员"></el-input>
        </el-form-item>
        <el-form-item label="票号">
          <el-input v-model="prolist.TicketNumber" placeholder="输入添加人员"></el-input>
        </el-form-item>
        <el-form-item label="工单类型">
          <el-input v-model="prolist.workoOderType" placeholder="输入添加人员"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="ShowMaterials" class="search-button">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-title">
      <h2>完工入库表</h2>
    </div>
    <!-- 生产计划列表（仅展示序号列相关结构） -->
    <div class="table-container">
      <el-table :data="planList" stripe ref="tableRef" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="id" label="序号"></el-table-column>
        <el-table-column prop="factory" label="工厂"></el-table-column>
        <el-table-column prop="workOrderNo" label="工单号"></el-table-column>
        <el-table-column prop="workoOderType" label="工单类型"></el-table-column>
        <el-table-column prop="finishedProductBatch" label="成品产品批次号"></el-table-column>
        <el-table-column prop="transactionTime" label="事务起始时间">
          <template #default="scope">
            {{ formatDate(scope.row.transactionTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="transactionEndTime" label="事务结束时间">
          <template #default="scope">
            {{ formatDate(scope.row.transactionEndTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="productionLine" label="产线"></el-table-column>
        <el-table-column prop="team" label="班组"></el-table-column>
        <el-table-column prop="shift" label="班次"></el-table-column>
        <el-table-column prop="materialCode" label="物料编码"></el-table-column>
        <el-table-column prop="materialDescription" label="物料编号说明"></el-table-column>
        <el-table-column prop="inventory" label="库存"></el-table-column>
        <el-table-column prop="freight" label=" 货位"></el-table-column>
        <el-table-column prop="plannedCompletions" label="计划完工数量"></el-table-column>
        <el-table-column prop="accessType" label="入出类型"></el-table-column>
        <el-table-column prop="unit" label="单位"></el-table-column>
        <el-table-column prop="inboundQuantity" label="实际入库数量"></el-table-column>
        <el-table-column prop="drinker" label="千升酒量"></el-table-column>
        <el-table-column prop="erpTickets" label="ERP工单"></el-table-column>
        <el-table-column prop="ticketNumber" label="票号"></el-table-column>
        <el-table-column prop="operator" label="操作人"></el-table-column>
        <el-table-column prop="businseeTime" label="生产日期">
          <template #default="scope">
            {{ formatDate(scope.row.businseeTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="operatingTime" label="生产日期">
          <template #default="scope">
            {{ formatDate(scope.row.operatingTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="right" label="操作">
          <template #default="scope">
            <el-button type="text" @click="GetBYIdProductionPlanning(scope.row.id)" class="edit-button">编辑</el-button>
            <el-button type="text" @click="DeleteProductionPlanning(scope.row.id)" class="delete-button">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 20px">
      <el-pagination
        v-model:current-page="page.pageindex"
        v-model:page-size="page.pageSize"
        :page-sizes="[4, 8, 15, 20]"
        :background="true"
        prev-text="上一页"
        next-text="下一页"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total.totalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Materialread, Materialwrite } from '@/axios/axiosHelper';
import { ElMessage, ElMessageBox } from 'element-plus';
import router from '@/router';
import axios from 'axios';

// 定义搜索表单数据
const prolist = ref({
  factory: '',
  transactionTime: '',
  transactionEndTime: '',
  workOrderNo: '',
  finishedProductBatch: '',
  productionLine: '',
  team: '',
  shift: '',
  materialCode: '',
  accessType: '',
  TicketNumber: '',
  workoOderType: '',
});

// 定义分页总数
const total = ref({
  totalCount: 0,
  totalPage: 0,
});

// 定义分页对象
const page = ref({
  pageindex: 1,
  pageSize: 15,
});

const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};

// 模拟生产计划列表数据
const planList = ref([
  {
    "id": 0,
    "factory": "",
    "workOrderNo": "",
    "workoOderType": "",
    "finishedProductBatch": "",
    "transactionTime": "",
    "transactionEndTime": "",
    "productionLine": "",
    "team": "",
    "shift": "",
    "materialCode": "",
    "materialDescription": "",
    "inventory": "",
    "freight": "",
    "plannedCompletions": '',
    "accessType": "",
    "unit": "",
    "inboundQuantity": '',
    "drinker": '',
    "erpTickets": "",
    "ticketNumber": "",
    "operator": "",
    "businseeTime": "",
    "operatingTime": "",
    "isDel": false
  }
]);

// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);

// 选中的 ID 列表
const checkedIds = ref([]);

const ShowMaterials = () => {
  Materialread.get("p-read/api/CompletedStorage/GetCompletedStorage", {
    params: {
      pageindex: page.value.pageindex,
      pageSize: page.value.pageSize,
      factory: prolist.value.factory,
      transactionTime: prolist.value.transactionTime,
      transactionEndTime: prolist.value.transactionEndTime,
      PickiworkOrderNongDate: prolist.value.workOrderNo,
      finishedProductBatch: prolist.value.finishedProductBatch,
      productionLine: prolist.value.productionLine,
      team: prolist.value.team,
      shift: prolist.value.shift,
      materialCode: prolist.value.materialCode,
      accessType: prolist.value.accessType,
      TicketNumber: prolist.value.TicketNumber,
      workoOderType: prolist.value.workoOderType,
    }
  }).then((res) => {
    planList.value = res.data.data.list;
    console.log("完工入库显示数据", res.data.data);

    total.value.totalCount = res.data.data.totalCount;
    total.value.totalPage = res.data.data.totalPage;
    // 重置全选状态和选中的 ID 列表
    allChecked.value = false;
    checkedIds.value = [];
    console.log(res.data.data);
  }).catch((error) => {
    console.error('接口请求失败:', error);
    ElMessage.error('数据获取失败，请稍后重试');
  });
};

// 编辑跳转修改
const GetBYIdProductionPlanning = (id) => {
  router.push({
    name: 'UpdateCompletedStorage',
    query: {
      id: id
    }
  }).catch((error) => {
    console.error('路由跳转错误:', error);
    ElMessage.error('跳转失败，请检查');
  });
  console.log(id);
};

const batchSaveDetails = () => {
  router.push({
    name: 'AddCompletedStorage',
  });
};

// 导入
// const handleImport = () => {
//   Materialread.get("/l-read/api/GetValues/ExportToExce2").then((res) => {
//     ElMessage.success('完工入库导入成功');
//   });
// };

// 单个删除功能
// 删除单条记录
// const DeleteProductionPlanning = async (id) => {
//   try {
//     const confirmResult = await ElMessageBox.confirm(
//       '确认删除该条记录？',
//       '提示',
//       {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }
//     );
//     if (confirmResult === 'confirm') {
//       const response = await axios.post(
//         `http://localhost:5293/api/CompletedStorage/DelCompletedStorage`,
//         {
//           params: {  }
//         }
//       );
//       if (response.data.code === 200) {
//         ElMessage.success('完工入库删除成功');
//         ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
//       } else {
//         ElMessage.error(`完工入库删除失败：${response.data.message}`);
//       }
//     }
//   } catch (error) {
//     if (error!== 'cancel') {
//       console.error('完工入库删除错误:', error);
//       ElMessage.error('完工入库删除失败，请检查网络或联系管理员');
//     }
//   }
// };
// 删除单条记录
const DeleteProductionPlanning = async (id) => {
  try {
    const confirmResult = await ElMessageBox.confirm(
      '确认删除该条记录？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    if (confirmResult === 'confirm') {
      const response = await Materialwrite.post(
        `p-write/api/CompletedStorage/DelCompletedStorage`,
        { id: id.toString() }, // 修改这里，将参数放在请求体中
        {
          params: {id: id.toString()} // 这里保持为空，因为参数已经在请求体中
        }
      );
      if (response.data.code === 200) {
        ElMessage.success('完工入库删除成功');
        ShowMaterials(); // 调用 ShowMaterials 方法刷新数据
      } else {
        ElMessage.error(`完工入库删除失败：${response.data.message}`);
      }
    }
  } catch (error) {
    if (error!== 'cancel') {
      console.error('完工入库删除错误:', error);
      ElMessage.error('完工入库删除失败，请检查网络或联系管理员');
    }
  }
};
const handleSizeChange = (val) => {
  page.value.pageSize = val;
  ShowMaterials();
};

const handleCurrentChange = (val) => {
  page.value.pageindex = val;
  ShowMaterials();
};

onMounted(() => {
  ShowMaterials();
});
</script>

<style scoped>
body {
  font-family: 'Arial', sans-serif;
  background-color: #f0f2f5;
  margin: 0;
  padding: 0;
}

.action-buttons {
  display: flex;
  justify-content: center;
  padding: 20px;
}

.import-button,
.add-button,
.search-button {
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.import-button {
  border: 1px solid #ccc;
  background-color: white;
  color: #333;
  margin-right: 10px;
}

.add-button {
  border: none;
  background-color: #42b983;
  color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-button {
  border: 1px solid #42b983;
  background-color: white;
  color: #42b983;
}

.search-section {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  margin: 0 20px 20px;
}

.page-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 20px;
}

.table-container {
  background-color: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  margin: 0 20px;
  max-height: 400px;
  overflow-y: auto;
}

.el-table {
  width: 100%;
  border-collapse: collapse;
}

.el-table__header-wrapper {
  background-color: #f4f4f4;
}

.el-table__header th {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ccc;
  color: #333;
}

.el-table__body td {
  padding: 10px;
  border-bottom: 1px solid #eee;
  color: #666;
}

.edit-button,
.delete-button {
  color: #42b983;
  padding: 5px 10px;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease, color 0.3s ease;
}

.edit-button:hover {
  background-color: #f0f9eb;
}

.delete-button:hover {
  color: red;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}
</style>